package com.sishu.njrtsdms.service.impl;


import com.sishu.njrtsdms.constant.Constants;
import com.sishu.njrtsdms.constant.cache.CacheConstants;
import com.sishu.njrtsdms.core.RedisCache;
import com.sishu.njrtsdms.domain.core.GenericServiceImpl;
import com.sishu.njrtsdms.exception.ServiceException;
import com.sishu.njrtsdms.jooq.codegen.tables.daos.ConfigDAO;
import com.sishu.njrtsdms.jooq.codegen.tables.pojos.Config;
import com.sishu.njrtsdms.service.ConfigService;

import org.jooq.types.ULong;
import org.springframework.stereotype.Service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class ConfigServiceImpl extends GenericServiceImpl<Config, ULong>
        implements ConfigService {

    private final ConfigDAO configDAO;

    private final RedisCache redisCache;


    public ConfigServiceImpl(ConfigDAO configDAO,
                             RedisCache redisCache) {
        super(configDAO);
        this.configDAO = configDAO;
        this.redisCache = redisCache;
    }

    @Override
    public boolean selectCaptchaEnabled() {
        String captchaEnabled = selectConfigByKey(Constants.SYS_ACCOUNT_CAPTCHA_ENABLED_CONFIG_KEY);
        if (StrUtil.isEmpty(captchaEnabled)) {
            return true;
        }
        return Convert.toBool(captchaEnabled);
    }


    @Override
    public String selectConfigByKey(String configKey) {
        var configValue = Convert.toStr(redisCache.getCacheString(getCacheKey(configKey)));
        if (StrUtil.isNotEmpty(configValue)) return configValue;

        var retConfigOpt = configDAO.fetchOptionalByConfigKey(configKey);
        Config retConfig = retConfigOpt
                .orElseThrow(() -> new ServiceException("配置不存在,请确认键名是否正确"));

        redisCache.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue());
        return retConfig.getConfigValue();
    }


    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey) {
        return CacheConstants.SYS_CONFIG_KEY + configKey;
    }
}